import OSS from 'ali-oss';
import { Toast } from 'antd-mobile';
import { v4 as uuidv4 } from 'uuid';
import md5 from 'md5';
const { uploadWorldImage } = $globalServicer('world')
// 生成随机文件名的函数
const generateRandomFileName = (file) => {
  const ext = file.name.split('.').pop() || '';
  const uuid = uuidv4();
  const hashName = md5(`${uuid}`);
  console.log("🚀 ~ generateRandomFileName ~ hashName:", hashName)
  return `images/${hashName}.${ext}`;
};

// export const handleImageUpload = async (file) => {
//   try {
//     const bucket = 'hslai'
//     const region = 'oss-cn-beijing'
//     const client = new OSS({
//       region: region,
//       authorizationV4: true,
//       accessKeyId: "LTAI5tJr3jkPPYYRkemL8G5Z",
//       accessKeySecret: "bOKRCBzI9KE8E88RsUPTNb9CFbhSfQ",
//       bucket: bucket,
//       secure: true,
//       cors: true,
//     });

//     // 使用随机文件名
//     const fileName = generateRandomFileName(file);
//     // 上传文件
//     const result = await client.put(fileName, file, {
//       headers: {
//         'Access-Control-Allow-Origin': '*',
//         'Content-Type': file.type
//       }
//     }).then(res => {
//       return {
//         url: res.url,
//         path: fileName
//       }
//     })
//     return result
//   } catch (error) {
//     console.error('上传失败：', error);
//     Toast.show({
//       icon: 'fail',
//       content: '图片上传失败，请重试',
//     });
//     throw error;
//   }
// };

export const handleImageUpload = async (file) => {
  // 检查文件大小，限制为2MB (2 * 1024 * 1024 bytes)
  const maxSize = 2 * 1024 * 1024; // 2MB
  if (file.size > maxSize) {
    throw new Error('图片大小超过2MB限制');
  }

  const formData = new FormData();
  formData.append('file', file);
  const res =  await uploadWorldImage(formData)
  return {
    path: res.url,
    url: res.url
  }
}
